package com.hdw.common.db;

import com.hdw.common.util.DBUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author: zhangyao
 * @create:2020-04-07 11:20
 **/
@Aspect
@Component
public class DataSourceAop {

    @Pointcut("@annotation(com.hdw.common.db.RoutingDataSource) || @within(com.hdw.common.db.RoutingDataSource)")
    public void routingDataSourcePointcut() {
    }

    @After("routingDataSourcePointcut()")
    public void afterAspect(JoinPoint joinPoint) {
        DynamicDataSource.clearDataSource();
    }

    @Before("routingDataSourcePointcut() && @annotation(routingDataSource)")
    public void beforeAspect(JoinPoint joinPoint, RoutingDataSource routingDataSource) {
        if (DBUtil.DB_DW.equals(routingDataSource.IdDb())) {
            DynamicDataSource.setDataSource(DBUtil.DB_DW);
        } else {
            DynamicDataSource.setDataSource(routingDataSource.IdDb());
        }
    }

    @AfterReturning("routingDataSourcePointcut()")
    public void afterReturningAspect(JoinPoint joinPoint) {
        DynamicDataSource.clearDataSource();
    }


    @AfterThrowing("routingDataSourcePointcut()")
    public void afterThrowingAspect(JoinPoint joinPoint) {
        DynamicDataSource.clearDataSource();
    }
}
